
import { getList, uploadFile, downFile ,remove} from '@/api/file/fileUploadAndDown'
import permission from '@/directive/permission/index.js'
import QRCode from 'qrcode';

export default {
  directives: { permission },
  data() {
    return {
      headers: { "Content-Type": "multipart/form-data;charset=UTF-8" },
      deptList: [],
      roleList: [],
      isAdd: true,
      checkedPermissionKeys: [],
      permissons: [],
      // defaultProps: {
      //   id: 'id',
      //   label: 'name',
      //   children: 'children'
      // },
      form: {
        id: 0,
        file: null,
        remarks: ''
      },
      formData: undefined,
      uploadModalVisible: false,
      listQuery: {
        pageIndex: 1,
        pageSize: 10,
        name: undefined
      },
      total: 0,
      list: null,
      listLoading: true,
      selRow: {},
      allInvoices: {},
      allClues: {},
      selectCluesItem: null,
    }
  },
  //   filters: {
  //     statusFilter(status) {
  //       const statusMap = {
  //         published: 'success',
  //         draft: 'gray',
  //         deleted: 'danger'
  //       }
  //       return statusMap[status]
  //     }
  //   },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.fetchData()
    },
    fetchData() {
      this.listLoading = true;

      // Assuming getList returns a Promise
      getList(this.listQuery).then(async (data) => {
          this.list = data.data;

          // Generate QR Code for each item in the list
          for (const item of data.data) {
            try {
              item.qrCodeDataUrl = await this.generateQRCodeCanvas(item.fileName);
            } catch (error) {
              console.error('Error generating QR Code:', error);
            }
          }
          await this.generateQRCodeCanvas(data.data[0].fileName)
          console.log(this.list, "this.list")

          this.listLoading = false;
          this.total = data.totalCount;
        })
        .catch((error) => {
          console.error('Error fetching data:', error);
          this.listLoading = false;
        });
    },
    search() {
      this.fetchData()
    },
    reset() {
      this.listQuery.name = ''
      this.fetchData()
    },
    handleFilter() {
      this.getList()
    },
    fetchNext() {
      this.listQuery.pageIndex = this.listQuery.pageIndex + 1
      this.fetchData()
    },
    fetchPrev() {
      this.listQuery.pageIndex = this.listQuery.pageIndex - 1
      this.fetchData()
    },
    fetchPage(pageIndex) {
      this.listQuery.pageIndex = pageIndex
      this.fetchData()
    },
    changeSize(pageSize) {
      this.listQuery.pageSize = pageSize
      this.fetchData()
    },
    handleCurrentChange(currentRow, oldCurrentRow) {
      this.selRow = currentRow
    },

    // generateQRCode(filePath) {
    //   return new Promise((resolve, reject) => {
    //     QRCode.toDataURL(filePath, (error, dataUrl) => {
    //       if (error) {
    //         reject(error);
    //       } else {
    //         resolve(dataUrl);
    //       }
    //     });
    //   });
    // },
    generateQRCodeCanvas(fileName) {
      console.log(fileName, "this.filePath")
      try {
        let opts = {
          errorCorrectionLevel: "H",
          type: "image/png",
          quality: 0.3,
          margin: 6,
          width: 200, // Adjusted width for the table
          height: 180, // Adjusted height for the table
          text: `http://siyin.icu:7215/file/fileUpload/down?fileName=${fileName}`, // Use fileName as part of the URL
          color: {
            dark: "#333333",
            light: "#fff"
          }
        };
        var QRCodeMsg = `http://siyin.icu:7215/file/fileUpload/down?fileName=${fileName}`; //生成的二维码为URL地址js
        //let msg = document.getElementById('QRCode_' + fileName);
        console.log('QRCode_' + fileName)
        console.log( QRCodeMsg)
        var canvas = document.getElementById('QRCode_' + fileName);
         QRCode.toCanvas(canvas, QRCodeMsg, opts, function (error) {
          //console.log(error)
        });
        //await QRCode.toCanvas(canvas, opts);
      } catch (error) {
        throw error;
      }
    },
    async downloadFile(filePath) {
      try {
        // Construct the download link
        const downloadLink = `http://siyin.icu:7215/file/fileUpload/down?fileName=${encodeURIComponent(filePath)}`;

        // Create a hidden link element
        const link = document.createElement('a');
        link.href = downloadLink;
        link.target = '_blank'; // Open in a new tab
        link.download = ''; // You can specify a default filename here if needed

        // Trigger a click event on the link to start the download
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } catch (error) {
        console.error('Error downloading file:', error);
        // Handle error as needed
      }
    },
    openUploadModal() {
      this.uploadModalVisible = true;
    },
    closeUploadModal() {
      this.uploadModalVisible = false;
      this.form = {
        id: 0,
        file: null,
        remarks: ''
      }
      this.formData=undefined;
    },
    handleFileUpload({ file }) {
      this.importLoading = true
      // 通过URL.createObjectURL可以获取文件的真实url，需要slice是因为前缀有blob:
      //const fileUrl = URL.createObjectURL(file).slice(5)// 类型通过则把文件变成formData的形式，因为文件一般是formData数据
      // if(!this.form.file){
      //   this.handleUpload()
      // }
      this.form.file = file
      
      // 发送网络请求... 
      console.log(this.formData, 'formData')
      console.log(file, 'file')
    },
    handleUpload() {
      console.log(this.form, 'this.form')
      if (!this.form.file) {
        console.error('No file selected.');
        return;
      }
      this.formData = new FormData();
      this.formData.append('file', this.form.file);
      this.formData.append('remarks', this.form.remarks);
      console.log(this.formData, 'this.formData')
      uploadFile(this.formData).then(res => {
        console.log(res, 'res')
        if(res>0){
          this.$message({
            message: '提交成功',
            type: 'success'
          })
          //this.closeUploadModal()
          // this.fetchData()
          // this.closeUploadModal()
        }
      })
    },
    downloadFile3(fileName) {
      // 模拟下载请求，可以使用实际的下载接口
      // 此处使用 window.open 模拟新窗口打开文件的行为
      downFile(fileName).then(data => {
        console.log(data, 'file')
      })
      //window.open();
    },
    deleteFile(id){
      console.log(id, 'id')
      if (true) {
          
          this.$confirm('确定删除该记录?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
          }).then(() => {
              remove(id).then(response => {
                  this.$message({
                      message: '删除成功',
                      type: 'success'
                  })
                  this.fetchData()
              }).catch(err => {
                  this.$notify.error({
                      title: '错误',
                      message: err
                  })
              })
          }).catch(() => {
          })
      }
    }
    
  },


}
